#include <rtconfig.h>
#include <rtdevice.h>
#include "vector_parser.h"
#include <ulog.h>
#include "string.h"


extern void OpenTestVector(void);
extern int  GetNextPattern(void);
rt_uint8_t buf_out[32];
static int32_t  g_i32DigestLength = 0;

int  do_compare(uint8_t *output, uint8_t *expect, int cmp_len)
{
    int   i;

    if(memcmp(expect, output, (size_t)cmp_len))
    {
        LOG_E("\nMismatch!! - %d\n", cmp_len);
        for(i = 0; i < cmp_len; i++)
            LOG_E("0x%02x    0x%02x\n", expect[i], output[i]);
        return -1;
    }
    return 0;
}


int32_t RunSHA(void)
{
    uint32_t  au32OutputDigest[8];

    struct rt_hwcrypto_ctx *ctx;
    LOG_I("Sha1 Test:%d byte test start\r\n",(uint32_t)g_i32DataLen / 8);
    /* 创建一个 hash 类型的上下文 */
    ctx = rt_hwcrypto_hash_create(rt_hwcrypto_dev_default(), HWCRYPTO_TYPE_SHA1);
	
		rt_hwcrypto_hash_reset(ctx);
    if (ctx == RT_NULL)
    {
        LOG_E("create hash[%08x] context err!", HWCRYPTO_TYPE_SHA1);
        return -1;
    }
    /* 将输入数据进行 hash 运算 */
    rt_hwcrypto_hash_update(ctx, g_au8ShaData, (uint32_t)g_i32DataLen / 8);
 
    /* 获得运算结果 */
    rt_err_t  err = rt_hwcrypto_hash_finish(ctx, buf_out, 32);    


    rt_hwcrypto_hash_destroy(ctx);

  //  LOG_E("Key len= %d bits\n", g_i32DataLen);

    /* Compare calculation result with golden pattern */
    if(do_compare(&buf_out[0], &g_au8ShaDigest[0], g_i32DigestLength) < 0)
    {
        LOG_E("Compare error!\n");
        while(1);
    }else{
        LOG_I("Compare OK!\n");
    }
    LOG_I("Sha1 Test:%d byte test end\r\n",(uint32_t)g_i32DataLen / 8);
    return 0;
}


int sha1_test(int argc, char **argv)
{
    LOG_E("sha1 test start\r\n");
    OpenTestVector();
    while(1)
    {
        /* Get data from test vector to calcualte and
           compre the result with golden pattern */
        if(GetNextPattern() < 0)
            break;

       RunSHA();
    }
    LOG_E("sha1 test end\r\n");    
}
MSH_CMD_EXPORT(sha1_test,  sha1 test);

